/*
 * jquery.js是必须的
 */

var baseGlobal = {};

//ajax全局事件
var webStatus = {
    200:"200 -> 请求成功",
    302:"302 -> 临时跳转",
    403:"403 -> 登录超时",
    404:"404 -> 请求地址错误",
    500:"500 -> 请检查服务端",
    505:"505 -> 请检查服务端"
};

$(document).ajaxStart(function (e) {
    var $el = $(e.target.activeElement);

}).ajaxSend(function (e, jqXHR, options) {

    //全局请求添加token
    var  token=$('[name="csrf-token"]').attr('content');
    if(typeof options.token == 'undefined'){
        if(token) options.data =options.data+'&_token='+token;
    }

}).ajaxError(function (e, xhr, opts) {
    switch (xhr.status){
        case 403:
            console.log(webStatus[403]);
            window.location.href='/user/login?return_url='+window.location.href;
            break;
        case 404:
            console.log(webStatus[404]);
            break;
        case 500:
            console.log(webStatus[500]);
            break;
        default:
            break;
    }


}).ajaxSuccess(function (e, xhr, opts) {
    var $el = $(e.target.activeElement);

    if (xhr.responseJSON && xhr.responseJSON.message && !$el.hasClass('diy-error')) {
        layer.msg(xhr.responseJSON.message, {
            offset: '10px'
        });
    }

}).ajaxComplete(function (e, jqXHR, options) {

}).ajaxStop(function () {

});



if(!Array.indexOf)
{
    Array.prototype.indexOf = function(obj)
    {
        for(var i=0; i<this.length; i++)
        {
            if(this[i]==obj)
            {
                return i;
            }
        }
        return -1;
    }
}

//jq扩展要放前面 如果比较多的话 单独拉出去
$.extend($.fn,{
    //页面顶部出现浮动提示
    notify:function(msg,state,config){
        var opts = $.extend({
            disabled:false,
            autoHidden:true,
            delay:2500,
            mask:false,
            posStyle:"",
            forNew:true,            //一直为新插入
            callback:function(){}
        },config);
        var $this = $(this),$notifyLr = "",tempHtml="";
        var tpl = '<div class="bl-notify notify-${id}">'
            +   '<div class="notify-con notify-${state}">'
            +       '<div class="notify-inner"><i class="f-icon success">&#xe616;</i><i class="f-icon error">&#xe686;</i><i class="f-icon loading animate-spin">&#xe6a2;</i>${notify}</div>'
            +       '<div class="notify-mask"></div>'
            +   '</div>'
            +'</div>';
        if(!$("#notifyLr").length){
            $("body").append('<div class="notify-wrap" id="notifyLr"></div>');
        }
        $notifyLr = $("#notifyLr");
        //设置遮罩外套样式
        opts.posStyle ? $notifyLr.attr("style",opts.posStyle) : $notifyLr.attr("style","display:block");
        opts.mask ? $notifyLr.addClass("notify-wrap-mask") : $notifyLr.removeClass("notify-wrap-mask");

        this.tempTime = 0;
        this.init = function(){
            var id = new Date().getTime(),
                thisNotifyData = "",
                thisCurNotify;

            $this.data("notify",id);
            thisNotifyData = id;
            (opts.forNew) ? this.appendHtml(thisNotifyData,state) : this.upMsg(msg,state);
            /*if( !$this.data("notify") ){
             $this.data("notify",id);
             thisNotifyData = id;
             this.appendHtml(thisNotifyData,state);
             }else{
             (opts.forNew) ? this.appendHtml(thisNotifyData,state) : this.upMsg(msg,state);
             }*/
        };
        this.upMsg = function(msg,state){
            var dataNotify = $this.data("notify");
            clearTimeout(this.tempTime);
            var tempHtml = tools.htmlTemplate( tpl,{"id":dataNotify,"state":state,"notify":msg} );
            $notifyLr.html(tempHtml);

            this.timeEnd(dataNotify);

            tools.log("upMsg");
        };
        this.timeEnd = function(thisNotifyData){

            var thisCurNotify = $(".notify-"+thisNotifyData);
            if(opts.autoHidden){
                clearTimeout(this.tempTime);
                this.tempTime = setTimeout(function(){
                    tools.log("timeEnd");

                    thisCurNotify.animate({"opacity":0},400,function(){
                        $(this).remove();
                    });
                    //$notifyLr.hide();
                    //$this.data("notify","");
                    opts.disabled &&  $this.removeClass("disabled");
                    opts.callback(thisCurNotify);
                },opts.delay);
            }
        };
        this.appendHtml = function(thisNotifyData,state){
            opts.disabled &&  $this.addClass("disabled");
            tempHtml = tools.htmlTemplate( tpl,{"id":thisNotifyData,"state":state,"notify":msg} );
            $notifyLr.show().append(tempHtml);
            this.timeEnd(thisNotifyData)
        };
        this.close = function(){
            //thisCurNotify.remove();
            $notifyLr.hide();
        };
        this.destroy = function(){
            $notifyLr.hide();
            $notifyLr.remove();
        };
        this.init();
        return this;
    },

    //模拟checkbox
    sCheckbox:function(curClass){
        var This= this,curClassName = curClass || "s-sChecked";
        this.setState = function($el,$wrap){
            $el.prop("checked") ? $wrap.addClass(curClassName) : $wrap.removeClass(curClassName);
        };
        return this.each(function(){
            var $this = $(this),$ckIcon =$this.siblings(".ck-icon"), $pEl = $this.closest("label");
            This.setState($this,$pEl);
            $this.off("change.sCheckbox").on("change.sCheckbox",function(){
                This.setState($this,$pEl);
            });
        })
    },

    //模拟radio
    sRadio:function(call){
        var This= this;
        this.setState = function($el,$wrap){
            if($el.prop("checked")){
                var parentEl = (typeof call =="string") ? $wrap.closest(call) : false;
                $wrap.addClass("s-rChecked");
                if(parentEl&&parentEl.length){
                    parentEl.siblings(call).find("label").removeClass("s-rChecked");
                }else{
                    $wrap.siblings("label").removeClass("s-rChecked");
                }
                if(call && (typeof call =="function")){
                    call($el,$wrap);
                }
            }
        };
        return this.each(function(i){
            var $this = $(this),
                $ckIcon =$this.siblings(".ck-icon"),
                $pEl = $this.closest("label");
            var _id =this.name+i;
            this.id = _id;
            $pEl.attr("for",_id);
            This.setState($this,$pEl);
            $this.off("change.rCheckbox").on("change.rCheckbox",function(){
                This.setState($this,$pEl);
            });
        })
    },

    //下拉菜单
    sSelect:function(config){
        var opts = $.extend(true,{
            type:"menu",
            selectedBack:function(that,val,txt){}
        },config);
        var This = this;
        var pos = {
            "l-b":{"left":"0"},
            "r-b":{"right":"0"}
        };
        this.els = $(".bl-ddmenu");
        this.menuConW = 0;
        this.isClick = 0;
        this.setPos = function($this,$menuCon,$menuBtn,target){
            var _pos = $this.data("pos") || "l-b",
                cssObj = {};
            if($this.data("append")){
                var targetId = $this.data("target"),
                    $target = $("#"+targetId),
                    newPos = $menuBtn.offset().left;
                //tools.log(newPos);

                if(_pos=="r-b"){
                    newPos = {"left":$menuBtn.offset().left + $menuBtn.outerWidth() - $target.width()};
                }else{
                    newPos = {"left":$menuBtn.offset().left};
                }
                cssObj = $.extend({"top":($menuBtn.offset().top+$menuBtn.outerHeight()),"margin-top":-1,"display":"none"},newPos);

                $target.css(cssObj);
            }else{
//              cssObj = $.extend({"padding-top":$menuBtn.outerHeight(),"margin-top":-1},pos[_pos]);
                cssObj = $.extend({"padding-top":0,"margin-top":$menuBtn.outerHeight()-1},pos[_pos]);
                $menuCon.css(cssObj);
            }

        };
        this.free = function($menu,$menuCon){
            var append = $menu.data("append");
            if(append){
                var randomNum = 1 + Math.round(Math.random() * 100-1); //1-100随机数
                var id = "sSelectFree"+randomNum;
                $menu.data("target",id);
                $(append).append('<div class="menu-con menu-free" id="'+id+'" style="display:none;">'+$menuCon.html()+'</div>');
            }
        };
        this.Switch = function($el){
            if($el.hasClass("menu-not")){ return }
            var target = $el.data("target"),$target;
            if(target){
                $target = $("#"+target);
                $target.is(":hidden") ? $target.show() : $target.hide();
            }else{
                $el.toggleClass("menu-on");
            }
            this.setZ($el);
        };
        this.setZ = function($el){
            //IE6 7 如果父级相对定位但是没有z-index的话，会出现下方的 同级相对定位遮挡
            if(tools.Browser().msie&&tools.Browser().ver<8){
                var $pEl = "",i=0;
                var forParent = function(jqEl){
                    i++;
                    $pEl = jqEl.parent();
                    if($pEl.css("position").toLowerCase() == "static"){
                        tools.log($pEl.css("position").toLowerCase());
                        if(i<1){
                            forParent($pEl)
                        }
                    }
                };
                if($el.length==0) return false;
                forParent($el);
                $el.hasClass("menu-on") ? $pEl.css({"z-index":"10"}) : $pEl.css({"z-index":""});
            }
        };
        this.docEvent = function(){
            $(document).on("click",function(e){
                if(!$(e.target).closest(".bl-ddmenu").length){
                    This.els.removeClass("menu-on");
                    $(".menu-free").hide();
                    This.setZ(This.els);
                }
            });
        };
        this.docEvent();
        return this.each(function(i){
            var $this = $(this),
                event = $this.data("event") || "click.menuBtn",
                //zIndex = $this.eq(0).css("z-index"),
                append = $this.data("append")||false,
                $menuInput = $this.find(".menu-input"),
                menuInputVal = $menuInput.val(),
                $menuBtn = $this.find(".menu-btn"),
                $menuBtnText = $menuBtn.children("span"),
                $menuCon = $this.find(".menu-con"),
                $li = $this.find("li"),
                defTxt = $menuBtnText.text();

            this.menuConW = $menuCon.width();
            This.free($this,$menuCon);

            //设置宽度
            if(tools.Browser().msie&&tools.Browser().ver<8){
                if($this.hasClass("noSetWidth")){ return }
                if($menuBtnText.length){
                    var _w = $menuBtnText.width()+15;
                    //$menuBtn.width(_w);
                    //$menuCon.width(_w);
                }
            }

            //设置初始值
            if(menuInputVal){
                var $el = $li.filter("[data-value='"+menuInputVal+"']"),
                    val = $el.data("value"),
                    txt = $el.text();
                $menuInput.val(val);
                $menuBtnText.text(txt).removeClass("placeholder");
            }else{
                $menuInput.val(""); //初始的时候设置为空
            }
            //设置z轴
            //zIndex-- ;
            //$this.css({'z-index':zIndex-i});

            //绑定事件
            if(event=="hover"){
                $this.hover(
                    function(){
                        This.setPos($this,$menuCon,$menuBtn);
                        //This.Switch($this);
                        $this.addClass("menu-on");
                    },
                    function(){
                        //This.Switch($this);
                        $this.removeClass("menu-on");
                    }
                )
            }else{
                $this.off("click.menuBtn").on("click.menuBtn",".menu-btn",function(){
                    This.setPos($this,$menuCon,$menuBtn);
                    This.els.removeClass("menu-on");
                    This.Switch($this);
                }).off("focus.menu").on("focus.menu",".menu-input",function(){
                        $menuBtn.trigger("click");
                    });
            }
            if(append){
                $menuCon = $("#"+$this.data("target") );
            }
            $menuCon.off("click.menuLi").on("click.menuLi","li",function(){
                var that = $(this),
                    val = that.data("value"),
                    txt = that.text();
                //This.Switch($this);
                $this.removeClass("menu-on");
                This.setZ($this);
                if(that.hasClass("disabled")){return}
                if(opts.type=="menu"){
                    $menuInput.val(val);
                    $menuBtnText.text(txt).removeClass("placeholder");
                }
                opts.selectedBack(that,val,txt,$this);
            });

        })
    },
    ajaxEdit:function(callback,config){
        var opts = $.extend(true,{
            before:function(){}
        },config)
        return this.each(function(){
            var $this = $(this),
                $btnSave = $this.find(".btn-save");
            $this.on("click",".edit-btn",function(e){
                $this.addClass("ajax-edit-on");
                opts.before($this);
            })
            .on("click",".btn-save",function(){
                $this.removeClass("ajax-edit-on");
                typeof callback =="function" && callback($this);
            })
            .on("click",".btn-cancel",function(){
                $this.removeClass("ajax-edit-on");
            })
            .on("focus",".ajax-input",function(){
                $(this).off("keyup.enter").on("keyup.enter",function(e){
                    (e.which==13) && $btnSave.trigger("click");
                })
            })
        })
    },
    //导航菜单
    navMenu:function(config){
        var opts = $.extend({
            obj:'ul.navlevel',	//导航UL节点
            animateIn:"show",	//三种加入效果 show	SlideDown 	FadeIn
            animateOut:"hide"	//三种退出效果 hide 	SlideUp 	FadeOut
        },config);

        var This = this;

        this.Animate = {
            show:function(obj){
                obj.addClass("cur").children("ul:has('li')").show();
            },
            hide:function(obj){
                obj.removeClass("cur").children("ul").hide();
            },
            slideDown:function(obj){
                obj.addClass("cur").children("ul:has('li')").stop(true,true).slideDown(400);
            },
            slideUp: function(obj){
                obj.removeClass("cur").children("ul").stop(true,true).slideUp(100);
            },
            fadeIn:function(obj){
                obj.addClass("cur").children("ul:has('li')").stop(true,true).fadeIn(400);
            },
            fadeOut:function(obj){
                obj.removeClass("cur").children("ul").stop(true,true).fadeOut(100);
            }
        };

        //鼠标滑过show子导航
        return this.each(function(){
            var $this = $(this);
            $this.find("li").hover(function(){
                This.Animate[opts.animateIn]($(this));
            },function(){
                This.Animate[opts.animateOut]($(this));
            });
            //给当前初始状态增加标记 defCur
            $this.children("li").each(function(index, element) {
                var $this = $(this);
                if($this.hasClass("cur")){
                    $this.addClass("defCur");
                }
            });
            $this.mouseleave(function(){
                $this.children("li.defCur").addClass("cur");
            });
        });
    },

    //简单的tab $("外层ID").simTab("事件","延时","回调")
    simTab:function(Event,delay,callback,eq){
        var delayTime = delay ? delay : 0,
            time = 0,
            _event = Event||"click";
        return this.each(function(){
            var $this = $(this),
                $tabShow = $this.find(".tab-show"),
                $defTab = $this.find(".cur");

            $this.on(_event,".tab",function(){
                var that = $(this),index = that.index();
                if(that.hasClass('cur')) return false;
                clearTimeout(time);
                time = setTimeout(function(){
                    that.addClass("cur").siblings(".tab").removeClass("cur");
                    $tabShow.eq(index).show().siblings(".tab-show").hide();
                    callback && callback(that, index, $tabShow);
                },delayTime);
            }).on("mouseleave",".tab",function(){
                    clearTimeout(time)
                })
                .find(".tab").eq(eq||0).trigger(_event);
        })

    },

    tipEllipsis: function (callback, fontSize) {
        $("body").append('<span style="display: none; white-space: nowrap" id="tempTipEllipsis"></span>');
        var $tempTipEllipsis = $("#tempTipEllipsis");
        return this.each(function () {
            var $this = $(this),
                text = $this.text(),
                _fontSize = fontSize ? fontSize : $this.css("font-size");
            $tempTipEllipsis.text(text).css("font-size", _fontSize);

            if ($tempTipEllipsis.width() > $this.width()) {
                callback && callback($this, text);
            }
        });
    },
    loadMore:function(url,callback,config){
        var opts = $.extend({
            curPage:1,
            pageItemNumber:0,
            data:{}
        },config);
        var curPage = opts.curPage,
            pageItemNumber = opts.pageItemNumber;
        var $this = $(this),$target = $($this.data("target")),$loading = $target.next(".loading");
        $this.on("click",function () {
            if ($this.hasClass("disabled")) { return }
            $this.addClass("loading-show disabled");
            curPage++;
            $.ajax(url,{
                type:"GET",
                dataType:"html",
                data:$.extend({page:curPage},opts.data)
            })
            .done(function(res){
                if (res.replace(/\s/g, "").length > 10) {
                    curPage == 1 ? $target.html(res) : $target.append(res);
                    callback(res,curPage,$target);
                    $this.removeClass("loading-show disabled").css({"display":"block"});
                    $loading.hide();
                    if(pageItemNumber && $target.find("li").length < pageItemNumber*curPage){
                         $this.remove();
                    }
                } else {
                    curPage==1 && $loading.html('<div class="bl-nodata" style="margin:0;">暂无数据!</div>');
                    $this.removeClass("loading-show disabled").remove();
                }
            });
        });
        return this;
    },
    qrCode:function(config){
        var opts = $.extend(true,{
            text     :  window.location.href,  //设置二维码内容
            render   : "canvas",  //设置渲染方式
            width       : 200,     //设置宽度
            height      : 200,     //设置高度
            typeNumber  : -1,      //计算模式
            correctLevel: 0,        //纠错等级
            background  : "#ffffff",//背景颜色
            foreground  : "#000000" //前景颜色
        },config);
        opts.render = tools.html5support.canvas() ? "canvas" : "table";
        $(this).qrcode(opts);
    }
});

/*
 * 模拟 placeholder的jquery插件，IE6789的placeholder兼容方案
 * 作者：懒人建站http://www.51xuediannao.com/
 * 版本：v0.01
 * 2014-11-21
 * 注意：input的父级需要相对定位
 */
(function($){
    //$(".bl-form").find("[placeholder]").labelPlaceholder();
    $.extend($.fn,{
        labelPlaceholder:function(config){
            if( 'placeholder' in document.createElement('input') ){ return }   //支持placeholder的话返回
            var opts = $.extend({
                placeholder:"off",
                leftDeviation:0,
                tplLabel:'<label for="${for}" style="cursor: text;position: absolute; left: ${left}px; width: ${width}px;height: ${height}px!important; line-height:${lineHeight}px!important;font-size:${fontSize};${style};display:${display};text-indent:${tIndent}px" class="label-placeholder">${placeholder}</label>',
                styleLabel:'top:1px;color: #999;text-align: left!important;padding:0'
            },config);

            this.hidden = function(){
                $(this).siblings(".label-placeholder").hide();
            };

            return this.each(function(index){
                if(this.value.replace(/\s/g,"").length){ return }
                if(!this.id){this.id = this.name+index}
                var $this = $(this);
                $this.parent().css("position","relative");
                var fontSize = $this.css("font-size"),
                    left=($this.position().left-0)+opts.leftDeviation,
                    textIndent=$this.css("padding-left").replace("px","")-0,
                    W=$this.outerWidth()- opts.leftDeviation*2,
                    H = $this.outerHeight()-2,
                    placeholder = $this.attr("placeholder"),
                    forValue = this.id;
                //alert( $this.parents().html());
                var styleLabel = opts.styleLabel ? opts.styleLabel : "";
                var display = this.value ? "none" : "block";
                var temp = tools.htmlTemplate(opts.tplLabel,{"for":forValue,"placeholder":placeholder,"left":left,"width":W,"height":H,"lineHeight":H,"fontSize":fontSize,"style":styleLabel,"display":display,"tIndent":textIndent});
                $this.before(temp);

                var $labelPlaceholder =  $this.siblings(".label-placeholder");
                if(this.tagName.toLowerCase() == "textarea"){
                    $labelPlaceholder.css({top:"6px","margin-top":0,"line-height":"24px"});
                }
                $this.on("focus.placeholder",function(){
                    $labelPlaceholder.hide();
                }).on("blur.placeholder",function(){
                        if( $(this).val() ){
                            $labelPlaceholder.hide();
                        }else{
                            $labelPlaceholder.show();
                        }
                    });
                /*解决IE67 浏览器输入历史直接选择赋值时lable不隐藏bug*/
                $this.on('input',function(){
                    if(this.value.replace(/\s/g,"").length){ $labelPlaceholder.hide(); }
                });

                $this.on("destroy.labelPlaceholder",function(event){
                    $(this).siblings(".label-placeholder").hide();
                });

            });

        }
    });
})(jQuery);
/*$.fn.labelPlaceholder.hide = function(){
    alert($(this));
    this.siblings(".label-placeholder").hide();
};*/


